const fs = require('fs');
const path = require('path');
const Multer = require('koa-multer');
const Jimp = require('jimp');
const {AVATAR_PATH, COVER_PATH, PICTURE_PATH, WALL_PATH, ARTICLE_PIC_PATH} = require('../constants/file-path');
const errorTypes = require('../constants/error-types');

const avatarUpload = Multer({dest: AVATAR_PATH});
const avatarHandler = avatarUpload.single('avatar');

const coverUpload = Multer({dest: COVER_PATH});
const coverHandler = coverUpload.single('cover');

const pictureUpload = Multer({dest: PICTURE_PATH});
const pictureHandler = pictureUpload.array('picture', 9);

const wallUpload = Multer({dest: WALL_PATH});
const wallHandler = wallUpload.array('wall', 9);

const articlePicUpload = Multer({dest: ARTICLE_PIC_PATH});
const articlePicHandler = articlePicUpload.single('article_pic');

// 图片压缩
const pictureResize = async (ctx, next) => {
  // 1.获取所有图像信息
  const files = ctx.req.files;
  // 2.处理图像
  for (let file of files) {
    const destPath = path.join(file.destination, file.filename);
    Jimp.read(file.path).then(image => {
      image.resize(1280, Jimp.AUTO).write(`${destPath}-large`);
      image.resize(640, Jimp.AUTO).write(`${destPath}-middle`);
      image.resize(320, Jimp.AUTO).write(`${destPath}-small`);
    })
  }
  // 3.执行下一步
  await next();
}

// 删除壁纸
const removeWall = async (ctx, next) => {
  try {
    const {filename} = ctx.request.body;
    const realFilePath = `${WALL_PATH}/${filename}`;
    await fs.unlinkSync(realFilePath, err => console.log);
    await next();
  } catch (error) {
    console.log(error)
  }
}

module.exports = {
  avatarHandler,
  coverHandler,
  pictureHandler,
  pictureResize,
  wallHandler,
  articlePicHandler,
  removeWall
}
